package com.xuecheng.content.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.content.utils.SmsUtil;
import com.xuecheng.system.api.SystemClient;
import com.xuecheng.web.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;

import static com.xuecheng.content.utils.ConstantUtil.LOGINCODE;

/**
 * @author Sober_wxy
 * @date 2022/8/1 22:54
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

        @Autowired
        private RedisTemplate redisTemplate;

        @GetMapping("/smsMsg")
        public ResponseResult sendMsg(String phone){
                // 判断redis中是否存在
                // 从redis中获取短信验证码
                String code = (String) redisTemplate.opsForValue().get(phone);
                //如果redis中有，则短信验证码已发送并且有效，直接返回验证码已发送
                if (StrUtil.isNotEmpty(code)) {
                        return ResponseResult.okResult("短信已经发送，请稍后再试");
                }
                code = RandomUtil.randomNumbers(4);
                // 存入redis中 设置时效为 5分钟
                redisTemplate.opsForValue().set(LOGINCODE+phone, code , Duration.ofMinutes(5));
                //todo 上线再用 现在太费钱了
                try {
                        SendSmsResponse sendSmsResponse = SmsUtil.sendSms(phone, code);
                        if("ok".equalsIgnoreCase(sendSmsResponse.getCode())){
                                // 发送rebbitmq消息
                        }else {
                                throw new BusinessException(ErrorCode.ERROR);
                        }
                } catch (ClientException e) {
                        e.printStackTrace();
                        throw new BusinessException(ErrorCode.ERROR);
                }
                return ResponseResult.okResult();
        }
}
